package com.yekong.house.biz.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.yekong.house.biz.service.HouseService;
import com.yekong.house.biz.service.RecommendService;
import com.yekong.house.common.model.House;
import com.yekong.house.common.page.PageParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RecommendServiceImpl implements RecommendService {
    private static final String HOT_HOUSE_KEY = "hot_house";

    private static final Logger logger = LoggerFactory.getLogger(RecommendService.class);

    @Value("${redis.host}")
    private String redisHost;
    @Value("${redis.port}")
    private Integer redisPort;
    @Value("${redis.auth}")
    private String redisAuth;

    @Autowired
    private HouseService houseService;

    private Jedis jedis;

    @Override
    public void increase(Long id) {
        Jedis jedis = new Jedis(redisHost);
        jedis = new Jedis(redisHost, redisPort);
        jedis.auth(redisAuth);

        jedis.zincrby(HOT_HOUSE_KEY,1.0D,id+"");
        jedis.zremrangeByRank(HOT_HOUSE_KEY,10,-1);
        jedis.close();
    }

    @Override
    public List<Long> getHot() {
        try {
            Jedis jedis = new Jedis(redisHost);
            jedis = new Jedis(redisHost, redisPort);
            jedis.auth(redisAuth);

            Set<String> idSet = jedis.zrevrange(HOT_HOUSE_KEY, 0, -1);
            jedis.close();
            List<Long> ids = idSet.stream().map(Long::parseLong).collect(Collectors.toList());
            return ids;
        }catch (Exception e){
            return Lists.newArrayList();
        }
    }

    @Override
    public List<House> getHotHouse(Integer size) {
        House query = new House();
        List<Long> list = getHot();
        list = list.subList(0, Math.min(list.size(), size));
        if (list.isEmpty()) {
            return Lists.newArrayList();
        }
        query.setIds(list);
        final List<Long> order = list;
        List<House> houses = houseService.queryAndSetImg(query, PageParams.build(size, 1));

        Ordering<House> houseSort = Ordering.natural().onResultOf(hs -> {
            return order.indexOf(hs.getId());
        });
        return houseSort.sortedCopy(houses);
    }

    @Override
    public List<House> getLastest() {
        House query = new House();
        query.setSort("create_time");
        List<House> houses = houseService.queryAndSetImg(query, new PageParams(8, 1));
        return houses;
    }

}
